import React, { useEffect, useState } from 'react';

import { deviceGroupAddApi } from '@/api/deviceGroupApi';
import { type DeviceItem, deviceManagerListApi } from '@/api/deviceManagerApi';
import { equipmentProductListApi, type ProductItem } from '@/api/equipmentProductApi';
import { DeviceListStatus, getEnumItem, ProductNodeType } from '@/constants';
import { TableLocalePresets } from '@/utils/tableUtils';

import type { ActionType, ProColumns } from '@ant-design/pro-components';

interface AddDeviceDrawerProps {
  visible: boolean;
  groupId: string;
  onCancel: () => void;
  onSuccess: () => void;
}

const AddDeviceDrawer: React.FC<AddDeviceDrawerProps> = ({
  visible,
  groupId,
  onCancel,
  onSuccess,
}) => {
  const actionRef = React.useRef<ActionType>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<DeviceItem[]>([]);
  const [productOptions, setProductOptions] = useState<Array<{ label: string; value: string }>>([]);
  const [loading, setLoading] = useState(false);

  // 获取产品列表
  const fetchProductList = async () => {
    try {
      const res = await equipmentProductListApi({
        current: 1,
        size: 1000,
      });
      if (res.success) {
        const options = res.data.records.map((product: ProductItem) => ({
          label: product.productName || '',
          value: product.productName || '',
        }));
        setProductOptions(options);
      }
    } catch (error) {
      console.error('获取产品列表失败:', error);
    }
  };

  // 获取未分组的设备列表
  const fetchUnGroupedDevices = async (params: Record<string, unknown>) => {
    try {
      const res = await deviceManagerListApi({
        ...params,
        ungrouped: true, // 只获取未分组的设备
      });
      const responseData = res.data;

      if (Array.isArray(responseData)) {
        return {
          success: res.success,
          data: responseData,
          total: responseData.length,
        };
      } else if (responseData && typeof responseData === 'object') {
        const listData = responseData as API.ListType<DeviceItem>;
        return {
          success: res.success,
          data: listData.records ?? [],
          total: listData.total ?? 0,
        };
      }

      return {
        success: res.success,
        data: [],
        total: 0,
      };
    } catch (error) {
      console.error('获取未分组设备列表失败:', error);
      return {
        success: false,
        data: [],
        total: 0,
      };
    }
  };

  // 添加设备到分组
  const handleAddDevices = async () => {
    if (selectedRowKeys.length === 0) {
      window.$message.warning('请选择要添加的设备');
      return;
    }

    try {
      setLoading(true);
      const deviceIds = selectedRowKeys.map(key => Number(key)).filter(id => !isNaN(id));

      const res = await deviceGroupAddApi({
        groupId,
        deviceIds,
      });

      if (res.success) {
        window.$message.success(`成功添加 ${deviceIds.length} 台设备到分组`);
        setSelectedRowKeys([]);
        setSelectedRows([]);
        onSuccess();
        onCancel();
      } else {
        window.$message.error(res.message || '添加设备失败');
      }
    } catch (error) {
      console.error('添加设备失败:', error);
      window.$message.error('添加设备失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 获取设备状态标签
  const getStatusBadge = (status: number) => {
    const statusItem = getEnumItem(DeviceListStatus, String(status));
    return (
      <ABadge
        status={statusItem?.status as 'success' | 'processing' | 'default' | 'error' | 'warning'}
        text={statusItem?.label || '未知'}
      />
    );
  };

  // 获取节点类型标签
  const getNodeTypeTag = (nodeType: number) => {
    const nodeTypeItem = Object.values(ProductNodeType).find(item => item.value === nodeType);
    return nodeTypeItem ? nodeTypeItem.label : '未知';
  };

  // 表格列定义
  const columns: ProColumns<DeviceItem>[] = [
    {
      title: '设备code',
      dataIndex: 'code',
      key: 'code',
      width: 160,
      search: true,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 140,
      valueType: 'select',
      fieldProps: {
        options: productOptions,
        placeholder: '请选择产品',
        allowClear: true,
        showSearch: true,
        filterOption: (input: string, option?: { label: string; value: string }) =>
          option?.label?.toLowerCase().includes(input.toLowerCase()),
      },
    },
    {
      title: '设备状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      search: false,
      render: (_, record) => getStatusBadge(record.status || 0),
    },
    {
      title: '节点类型',
      dataIndex: 'nodeType',
      key: 'nodeType',
      width: 100,
      search: false,
      render: (_, record) => <ATag color="blue">{getNodeTypeTag(record.nodeType || 0)}</ATag>,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      search: false,
    },
  ];

  useEffect(() => {
    if (visible) {
      fetchProductList();
      setSelectedRowKeys([]);
      setSelectedRows([]);
    }
  }, [visible]);

  return (
    <ADrawer
      title="添加设备到分组"
      width={1000}
      open={visible}
      onClose={onCancel}
      footer={
        <div style={{ textAlign: 'right' }}>
          <ASpace>
            <AButton onClick={onCancel}>取消</AButton>
            <AButton
              type="primary"
              loading={loading}
              disabled={selectedRowKeys.length === 0}
              onClick={handleAddDevices}
            >
              添加选中设备 ({selectedRowKeys.length})
            </AButton>
          </ASpace>
        </div>
      }
    >
      <PProTable<DeviceItem>
        className="mh-table"
        actionRef={actionRef}
        columns={columns}
        request={fetchUnGroupedDevices}
        rowKey="id"
        search={{
          span: 6,
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
        }}
        scroll={{ x: 800 }}
        size="small"
        rowSelection={{
          selectedRowKeys,
          onChange: (keys, rows) => {
            setSelectedRowKeys(keys);
            setSelectedRows(rows);
          },
        }}
        locale={TableLocalePresets.device(actionRef)}
        tableAlertRender={({ selectedRowKeys }) => (
          <span>
            已选择 <strong>{selectedRowKeys.length}</strong> 台设备
          </span>
        )}
        tableAlertOptionRender={() => (
          <ASpace>
            <AButton
              size="small"
              onClick={() => {
                setSelectedRowKeys([]);
                setSelectedRows([]);
              }}
            >
              取消选择
            </AButton>
          </ASpace>
        )}
      />
    </ADrawer>
  );
};

export default AddDeviceDrawer;
